<template>
  <el-card>
    <template #header>
      <h3 v-text="t('log')"></h3>
    </template>

    <!-- 日志源选择区域 -->
    <el-row>
      <el-col>
        <el-select 
          v-model="logStore.currentLogSource" 
          @change="(value) => logStore.switchLogSource(value)"
          style="width: 100%;"
        >
          <el-option
            v-for="source in logStore.logSources"
            :key="source"
            :label="source"
            :value="source"
          />
        </el-select>
      </el-col>
    </el-row>

    <!-- 控制按钮区域 -->
    <el-row :gutter="8">
      <el-col :span="4">
        <el-button type="primary" @click="logStore.actionForDevel" style="width: 100%;">O</el-button>
      </el-col>
      <el-col :span="10">
        <el-button type="primary" @click="logStore.clearCurrentLog" style="width: 100%;">
          {{ t('clear') }}
        </el-button>
      </el-col>
       <el-col :span="10">
         <el-switch
           v-model="logStore.autoScroll"
           :active-text="t('auto_scroll')"
         />
       </el-col>
    </el-row>
    
    <!-- 日志内容显示区域 -->
    <el-row>
      <el-col :span="24">
        <div class="log-content">
          <template v-for="(log, index) in logStore.currentLogs" :key="index">
            <div class="log-line">{{ log }}</div>
          </template>
        </div>
      </el-col>
    </el-row>

  </el-card>
</template>

<script setup>
import { useLogStore } from '@/stores/log'
import { useLanguageStore } from '@/stores/language'
import { watch, nextTick } from 'vue'

const logStore = useLogStore()
const languageStore = useLanguageStore()

// 监听日志变化，实现自动滚动
watch(() => logStore.currentLogs, () => {
  if (logStore.autoScroll) {
    nextTick(() => {
      const logContent = document.querySelector('.log-content')
      if (logContent) {
        logContent.scrollTop = logContent.scrollHeight
      }
    })
  }
}, { deep: true })

// 监听自动滚动状态变化
watch(() => logStore.autoScroll, (newValue) => {
  if (newValue) {
    nextTick(() => {
      const logContent = document.querySelector('.log-content')
      if (logContent) {
        logContent.scrollTop = logContent.scrollHeight
      }
    })
  }
})

// 翻译函数
const t = (key) => {
  const translations = {
    'log': {
      'en': 'Log',
      'zh': '清单'
    },
    'clear': {
      'en': 'Clear',
      'zh': '清空'
    },
    'auto_scroll': {
      'en': 'Auto Scroll',
      'zh': '自动滚动'
    }
  }
  return translations[key]?.[languageStore.isChinese ? 'zh' : 'en'] || key
}
</script>

<style scoped>
.log-content {
  height: calc(100vh - 386px);
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 12px;
  background-color: var(--el-bg-color);
  font-family: 'Courier New', monospace;
  font-size: 11px;
  line-height: 1.4;
}
.log-line {
  word-break: break-all;
  white-space: pre-wrap;
  margin-bottom: 2px;
}
.log-line:last-child {
  margin-bottom: 0;
}
</style>
